package edu.friday.service.impl;

import edu.friday.model.SysMenu;
import edu.friday.model.vo.SysMenuVO;
import edu.friday.model.vo.SysUserVO;
import edu.friday.repository.SysMenuRepository;
import edu.friday.service.SysMenuService;
import edu.friday.utils.BeanUtils;
import edu.friday.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class SysMenuServiceImpl implements SysMenuService {
    @Autowired
    SysMenuRepository sysMenuRepository;

    @Override
    public Set<String> selectMenuPermsByUserId(Long userId){
        List<String> perms = sysMenuRepository.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for(String perm: perms){
            if(StringUtils.isNotEmpty(perm)){
                permsSet.addAll(Arrays.asList( perm.trim().split(",")));
            }
        }

        return permsSet;
    }

    @Override
    public List<SysMenu> selectMenuList(SysMenuVO menu, Long userId) {
        List<SysMenu> menuList= null;
        SysMenu sysMenu = new SysMenu();
        BeanUtils.copyPropertiesIgnoreEmpty(menu,sysMenu);
        Sort sort = Sort.by("parentId","orderNum");
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("menuName",ExampleMatcher.GenericPropertyMatchers.contains());
        Example example = Example.of(sysMenu,exampleMatcher);
        if(SysUserVO.isAdmin(userId)){
            menuList = sysMenuRepository.findAll(example,sort);
        }else {
            menuList = sysMenuRepository.selectMenuListByUserId(sysMenu,userId);
        }
        return menuList;
    }


}
